package org.mspring.mlog.web.module.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.mspring.mlog.entity.Twitter;
import org.mspring.mlog.service.TwitterImageService;
import org.mspring.mlog.service.TwitterService;
import org.mspring.mlog.service.WeiboService;
import org.mspring.platform.dao.Order.OrderType;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.query.QueryBuilder;
import org.mspring.platform.security.SecurityUtils;
import org.mspring.platform.security.entity.User;
import org.mspring.platform.security.exception.UNLoginException;
import org.mspring.platform.utils.ImageUtils;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.mspring.platform.weibo.exception.OAuthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author Gao Youbo
 * @since 2013-5-24
 */
@Widget
@RequestMapping("/t")
public class Web_TwitterWidget extends Web_AbstractWidget {

    private static final Logger log = LoggerFactory.getLogger(Web_TwitterWidget.class);

    @Autowired
    private TwitterService twitterService;
    @Autowired
    private TwitterImageService twitterImageService;
    @Autowired
    private WeiboService weiboService;
    @Autowired
    private TaskExecutor taskExecutor;

    @RequestMapping({ "/", "" })
    public String show(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "skin:/twitter";
    }

    @RequestMapping("/add")
    @ResponseBody
    public ResponseEntity add(@RequestParam(required = false) String content, @RequestParam(required = false) String pic, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        final User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录");
            return rsp;
        }
        if (StringUtils.isBlank(content)) {
            rsp.setSuccess(false);
            rsp.setMessage("请输入要发表的内容");
            return rsp;
        }

        try {
            Twitter twitter = new Twitter();
            twitter.setAuthor(user);
            twitter.setContent(content);
            twitter.setIp(RequestUtils.getRemoteIP(request));
            if (StringUtils.isNotBlank(pic)) {
                twitter.setImage(pic);
            }

            Long id = twitterService.insert(twitter);
            final Twitter result = twitterService.get(id);

            // 同步腾讯微博
            taskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        weiboService.add(user, result);
                    } catch (UNLoginException | OAuthException e) {
                        log.error("同步微博失败", e);
                    }
                }
            });

            rsp.setSuccess(true);
            rsp.setMessage("发表成功");
            rsp.put("twitter", new Twitter[] { result });
            return rsp;
        } catch (Exception e) {
            rsp.setSuccess(false);
            rsp.setMessage("发表内容失败" + e.getMessage());
            return rsp;
        }
    }

    /**
     * 获取Twitter
     *
     * @param page
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity get(@RequestParam(required = false) Integer page, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        if (page == null || page < 1) {
            page = 1;
        }
        Page<Twitter> twitterPage = new Page<>();
        twitterPage.setPageNo(page);
        twitterPage.setPageSize(12);
        twitterPage.addOrder("id", OrderType.DESC);
        twitterService.listPage(QueryBuilder.instance(Twitter.class), twitterPage);
        rsp.setSuccess(true);
        rsp.put("twitter", twitterPage.getResult());
        return rsp;
    }

    /**
     * 上传图片
     *
     * @param image
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/insert_image")
    @ResponseBody
    public ResponseEntity insertImage(@RequestParam("image") MultipartFile image, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录");
            return rsp;
        }
        // 限定上传图片的格式
        boolean isImage = ImageUtils.isImage(FilenameUtils.getExtension(image.getOriginalFilename()));
        if (!isImage) {
            rsp.setSuccess(false);
            rsp.setMessage("上传文件格式不正确");
            return rsp;
        }
        // 限定上传图片大小
        long size = image.getSize() / 1024;
        if (size > 512) {
            rsp.setSuccess(false);
            rsp.setMessage("上传图片大不能超过512K");
            return rsp;
        }
        try {
            String url = twitterImageService.upload(image.getBytes());
            rsp.setSuccess(true);
            rsp.put("image", url);
            return rsp;
        } catch (Exception e) {
            rsp.setSuccess(false);
            rsp.setMessage("上传图片失败" + e.getMessage());
            e.printStackTrace();
            return rsp;
        }
    }

    /**
     * 删除图片
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/delete_image")
    @ResponseBody
    public ResponseEntity deleteImage(@RequestParam(required = false) String image, HttpServletRequest request, HttpServletResponse response) {
        ResponseEntity rsp = new ResponseEntity();
        User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录");
            return rsp;
        }
        if (StringUtils.isBlank(image)) {
            rsp.setSuccess(false);
            rsp.setMessage("无法确认要删除的图片");
            return rsp;
        }
        twitterImageService.delete(image);
        rsp.setSuccess(true);
        return rsp;
    }
}
